import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import {
  reqResetPwd,
  reqVerifyAccount,
  reqVerifyCode
} from '@/service/module/forget-pwd'
import { Status } from '@/global/constant'
import { decryptData, encryptData } from '@/utils/encrypt'
import { IThunkState } from '@/global/type'

interface IState {
  info: any
  currentAccount: string
}

const initialState: IState = {
  info: {},
  currentAccount: ''
}

// 步骤一：验证是否存在账号
export const verifyAccountAction = createAsyncThunk<
  boolean,
  string,
  IThunkState
>('verifyAccount', async (account: string, { getState, dispatch }) => {
  const res = await reqVerifyAccount(account)
  // 用私钥去解密信息
  const privateKey = getState().app.privateKey
  const info = decryptData(privateKey, res.data)
  if (info) {
    dispatch(changeInfoAction(info))
  }
  // const info = encryptData(publicKey, res.data)
  return res.code === Status.SUCCESS
})

// 步骤二:验证验证码是否正确
export const verifyCodeAction = createAsyncThunk<void, any, IThunkState>(
  'verifyCode',
  async (params, { getState }) => {
    // 整理验证的参数
    const { password, confirmPassword, ...verifyParams } = params
    // 整理重置的参数
    const { code, data, ...resetParams } = params
    // 获取公钥
    const publicKey = getState().app.publicKey
    await reqVerifyCode(verifyParams)
    const encryptStr = encryptData(publicKey, resetParams)
    if (encryptStr) {
      await reqResetPwd(encryptStr)
    }
  }
)

const forgetPwdSlice = createSlice({
  name: 'forget-pwd',
  initialState,
  reducers: {
    // 第一步验证成功后返回的信息, 里面的邮件和手机号要在第二步用到
    changeInfoAction(state, { payload }) {
      state.info = payload
    },
    // 第一步验证成功后,将成功的用户名保存下来第二步用
    changeCurrentAccountAction(state, { payload }) {
      state.currentAccount = payload
    }
  }
})

export const { changeInfoAction, changeCurrentAccountAction } =
  forgetPwdSlice.actions
export default forgetPwdSlice.reducer
